package testtiles.state;

import static butines.core.math2d.Vector2DUtils.distanceSq;
import testtiles.object.Messages;
import testtiles.object.Unit;
import butines.core.math2d.Vector2D;
import butines.game.Message;

public class UnitMoveState extends AbstractState<Unit> {
	
	private static final UnitMoveState instance = new UnitMoveState();
	
	public static UnitMoveState getInstance() {
		return instance;
	}
	
	private float slowingDistance = 32f; 

	public boolean atTargetPoint(Unit unit, Vector2D targetPoint, float minDistance) {
		return distanceSq(unit.getPosition(), targetPoint) < minDistance * minDistance;
	}
	
	@Override
	public void enter(Unit unit) {
		unit.getSteering().getArrivel().setSlowingDistance(slowingDistance);
		unit.getSteering().getArrivel().setTarget(unit.getTargetPoint());
		unit.getSteering().getArrivel().on();
		unit.getSteering().getSeparation().on();
		unit.getSteering().getCohesion().on();
	}

	@Override
	public void leave(Unit unit) {
		unit.getSteering().getArrivel().off();
		unit.getSteering().getSeparation().off();
		unit.getSteering().getCohesion().off();
	}
	
	@Override
	public void execute(Unit unit) {
		
		if (atTargetPoint(unit, unit.getTargetPoint(), unit.getRadius())) {
			unit.doStay();
			return;
		}
		unit.getAnimations().getWalk().play();
	}

	@Override
	public boolean onMessage(Message message) {
		final Messages type = message.getType();
		switch (type) {
			case COLLIDED_WITH: {
				Unit obstacle = message.getSender();
				Unit owner = message.getReceiver();
				onCollidedWith(owner, obstacle);
				return true;
			}
		}
		
		return false;
	}

	private void onCollidedWith(Unit owner, Unit obstacle) {
//		if (atTargetPoint(obstacle, owner.getTargetPoint(), owner.getRadius() + obstacle.getRadius())) {
//			owner.doStay();
//		}
//		obstacle.getStateMachine().inState(stateClass)
//		if (!other.inState(UnitStayState.class)) {
//			if (other.getPosition().distance(owner.getTarget()) < other.getRadius()) {
//				owner.stay();
//			}
//		}
	}
	
	
}
